package com.example.controller;

import com.example.service.LoginService;
import com.example.vo.CommonReturn;
import com.example.vo.UserVo;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class LoginController {

    private final static Logger logger =
            LoggerFactory.getLogger(LoginController.class);

    private final LoginService login;

    public LoginController(LoginService loginService) {
        this.login = loginService;

    }

    @RequestMapping(value = "/admin/login", method = RequestMethod.POST)
    public CommonReturn login(@RequestBody @NotNull UserVo userVo) {

        logger.info("userVo:{}", userVo);
        try {
            Map<String, String> data = login.login(userVo.getUserName(), userVo.getPassword());
            return CommonReturn.success("登入成功", data);
        } catch (Exception e) {
            logger.error("error:{}", e.toString());
            String msg = e.toString();
            if (e instanceof IllegalArgumentException) {
                msg = e.getMessage();
            }
            return CommonReturn.error(msg);
        }

    }

}

